// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carts: [],
    selectAllStatus: true,
    totalPrice: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    setTimeout(() => {
      this.setData({
        carts: [
          { id: 1, title: '新鲜芹菜 半斤', image: '/image/s5.png', num: 2, price: 18, selected: false },
          { id: 2, title: '素米 25kg', image: '/image/s6.png', num: 1, price: 50, selected: true },
          { id: 3, title: '瓜子 500g', image: '/image/s4.png', num: 1, price: 12, selected: true }
        ]
      })
      this.changeAllSelectStatus()
      this.getTotalPrice()
    }, 1000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  selectList(e) {
    let index = e.currentTarget.dataset.index;
    let selected = `carts[${index}].selected`;
    this.setData({
      [selected]: !this.data.carts[index].selected
    })
    this.changeAllSelectStatus()
    this.getTotalPrice()
  },
  selectAll() {
    let selectAllStatus = this.data.selectAllStatus
    selectAllStatus = !selectAllStatus
    let carts = this.data.carts

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus
    }
    this.setData({
      selectAllStatus,
      carts
    })
    this.getTotalPrice()
  },
  changeAllSelectStatus(){
    let carts = this.data.carts
    for(let i =0;i<carts.length;i++){
      if(!carts[i].selected){
        this.setData({
          selectAllStatus:false
        })
        return ;
      }
    }
    this.setData({
      selectAllStatus:true
    })
  },
  getTotalPrice(){
    let carts = this.data.carts
    let totalPrice = 0
    for(let i = 0;i<carts.length;i++){
      if(carts[i].selected) totalPrice += carts[i].price*carts[i].num
    }
    this.setData({
      totalPrice
    })
  }
})